#include "server.h"

vector<bool> server::sock_arr(10000,false);

//构造函数
server::server(int port,string ip):server_port(port),server_ip(ip){}

//析构函数
server::~server(){
    for(int i=0;i<sock_arr.size();i++)
    {
	    if(sock_arr[i])
		close(i);
    }
    close(server_sockfd);
}

//服务器开始服务
void server::run(){
    //定义sockfd
    server_sockfd = socket(AF_INET,SOCK_STREAM, 0);

    //定义sockaddr_in
    struct sockaddr_in server_sockaddr;
    server_sockaddr.sin_family = AF_INET;//TCP/IP协议族
    server_sockaddr.sin_port = htons(server_port);//server_port;//端口号
    server_sockaddr.sin_addr.s_addr = inet_addr(server_ip.c_str());//ip地址，127.0.0.1是环回地址，相当于本机ip

    //bind，成功返回0，出错返回-1
    if(bind(server_sockfd,(struct sockaddr *)&server_sockaddr,sizeof(server_sockaddr))==-1)
    {
        perror("bind");//输出错误原因
        exit(1);//结束程序
    }

    //listen，成功返回0，出错返回-1
    if(listen(server_sockfd,20) == -1)
    {
        perror("listen");//输出错误原因
        exit(1);//结束程序
    }
    cout<<"欢迎使用服务器"<<endl;
    //客户端套接字
    struct sockaddr_in client_addr;
    socklen_t length = sizeof(client_addr);

    //不断取出新连接并创建子线程为其服务
    while(1){
        int conn = accept(server_sockfd, (struct sockaddr*)&client_addr, &length);
        if(conn<0)
        {
            perror("connect");//输出错误原因
            exit(1);//结束程序
        }
        cout<<"文件描述符为"<<conn<<"的客户端成功连接\n";
        sock_arr.push_back(conn);
        //创建线程
        thread t(server::RecvMsg,conn);
        t.detach();//置为分离状态，不能用join，join会导致主线程阻塞
    }
}

void selectitem(user user1,MYSQL *con,int conn)
{
         user user2;
         user2.result=1;
         cout<<"输入（ 项目名称）:"<<user1.itemname<<endl;
         string search="SELECT * FROM ITEM WHERE PNAME=\"";
         search+=user1.itemname;
         search+="\";";
         cout<<"sql语句:"<<search<<endl;
         auto search_res=mysql_query(con,search.c_str());
         auto result=mysql_store_result(con);
         int col=mysql_num_fields(result);//获取列数
         int row=mysql_num_rows(result);//获取行数
         if(search_res==0&&row!=0){
            user2.result=0;
            cout<<"查询成功\n";
            auto info=mysql_fetch_row(result);//获取一行的信息
            cout<<"查询到项目ID:"<<info[0]<<"查询到项目名称:"<<info[1]<<"负责人名字:"<<info[2]<< "金额:"<<info[3]<<endl;
            user2.itemid=atoi(info[0]);
            strcpy(user2.itemname,info[1]);
            strcpy(user2.name,info[2]);
            user2.count=atoi(info[3]);
            user2.audit=atoi(info[4]);
            send(conn,(char*)&user2,sizeof(user2),0);
         }
         else
         {
            send(conn,(char*)&user2,sizeof(user2),0);
         }
}

void server::HandleRequest(int conn,user user1){
    char buffer[1000];
    user user2;
    string name,pass;
    bool if_login=false;//记录当前服务对象是否成功登录
    string login_name;//记录当前服务对象的名字
    //连接MYSQL数据库
    MYSQL *con=mysql_init(NULL);
    mysql_real_connect(con,"127.0.0.1","debian-sys-maint","zi6bRCQqq53R1yvg","AccoutProject",0,NULL,CLIENT_MULTI_STATEMENTS);
    cout<<"当前连接数据库用户:debian-sys-maint"<<endl;
    cout<<"当前连接数据库地址:127.0.0.1"<<endl;
    if(user1.target==0){
        string search="INSERT INTO USER(NAME,PASSWORD,ROLE) VALUES (\"";
        search+=user1.name;
        search+="\",\"";
        search+=user1.pass;
        search+="\",\"";
        search+=std::to_string(user1.role);
        search+="\");";
        cout<<"sql语句:"<<search<<endl<<endl;
        if(mysql_query(con,search.c_str())!=0)
        {
             cout<<"插入失败"<<endl;
             user2.result=1;
             send(conn,(char*)&user2,sizeof(user2),0);
        }
    }
    else if(user1.target==1){
        string search="SELECT * FROM USER WHERE NAME=\"";
        search+=user1.name;
        search+="\";";
        cout<<"sql语句:"<<search<<endl;
        auto search_res=mysql_query(con,search.c_str());
        auto result=mysql_store_result(con);
        int col=mysql_num_fields(result);//获取列数
        int row=mysql_num_rows(result);//获取行数
        //查询到用户名
        if(search_res==0&&row!=0){
            cout<<"查询成功\n";
            auto info=mysql_fetch_row(result);//获取一行的信息
            cout<<"查询到用户名:"<<info[0]<<" 密码:"<<info[1]<<endl;
            //密码正确
            //cout<<user1.pass<<":"<<info[1]<<endl;
            if(strncmp(user1.pass,info[1],sizeof(info[1]))==0){
                cout<<"登录密码正确\n\n";
                string str1="ok";
                if_login=true;
                login_name=user1.name;//记录下当前登录的用户名
                send(conn,str1.c_str(),str1.length()+1,0);
            }
            //密码错误
            else{
                cout<<"登录密码错误\n\n";
                char str1[100]="wrong";
                send(conn,str1,strlen(str1),0);
            }
        }
        //没找到用户名
        else{
            cout<<"查询失败\n\n";
            char str1[100]="wrong";
            send(conn,str1,strlen(str1),0);
        }
    }
    else if(user1.target==2){
         //
         cout<<"输入（ 项目名称）:"<<user1.itemname<<endl;
         string search1="SELECT * FROM ITEM WHERE PNAME=\"";
         search1+=user1.itemname;
         search1+="\";";
         cout<<"sql语句:"<<search1<<endl;
         auto search_res=mysql_query(con,search1.c_str());
         auto result=mysql_store_result(con);
         int col=mysql_num_fields(result);//获取列数
         int row=mysql_num_rows(result);//获取行数
         if(search_res==0&&row!=0){
            user2.result=0;
            cout<<"查询成功\n";
            auto info=mysql_fetch_row(result);
            int count=atoi(info[3]);
            user1.count=-user1.count+count;
         }
         //
         string search="UPDATE ITEM SET ESM=";
         search+=std::to_string(user1.count);
         search+=" where PNAME=\"";
         search+=user1.itemname;
         search+="\";";
         cout<<"sql语句:"<<search<<endl;
         if(mysql_query(con,search.c_str())!=0)
         {
               cout<<"失败"<<endl;
               user2.result=1;
               send(conn,(char*)&user2,sizeof(user2),0);
         }
         send(conn,(char*)&user2,sizeof(user2),0);
    }
    else if(user1.target==3){
         //
         cout<<"输入（ 项目名称）:"<<user1.itemname<<endl;
         string search1="SELECT * FROM ITEM WHERE PNAME=\"";
         search1+=user1.itemname;
         search1+="\";";
         cout<<"sql语句:"<<search1<<endl;
         auto search_res=mysql_query(con,search1.c_str());
         auto result=mysql_store_result(con);
         int col=mysql_num_fields(result);//获取列数
         int row=mysql_num_rows(result);//获取行数
         if(search_res==0&&row!=0){
            user2.result=0;
            cout<<"查询成功\n";
            auto info=mysql_fetch_row(result);
            int count=atoi(info[3]);
            user1.count+=count;
         }
         //
         string search="UPDATE ITEM SET ESM=";
         search+=std::to_string(user1.count);
         search+=" where PNAME=\"";
         search+=user1.itemname;
         search+="\";";
         cout<<"sql语句:"<<search<<endl;
         if(mysql_query(con,search.c_str())!=0)
         {
               cout<<"失败"<<endl;
               user2.result=1;
               send(conn,(char*)&user2,sizeof(user2),0);
         }
         send(conn,(char*)&user2,sizeof(user2),0);
    }
    else if(user1.target==4){//新建项目
         cout<<"输入（ 项目名称，负责人名字，金额）:"<<user1.itemname<<user1.name<<user1.count<<endl;
         string search="INSERT INTO ITEM(PNAME,PRI,ESM,Idate) VALUES (\"";
         search+=user1.itemname;
         search+="\",\"";
         search+=user1.name;
         search+="\",";
         search+=std::to_string(user1.count);
         search+=",now());";
         cout<<"sql语句:"<<search<<endl<<endl;
         if(mysql_query(con,search.c_str())!=0)
         {
               cout<<"插入失败"<<endl;
               user2.result=1;
               send(conn,(char*)&user2,sizeof(user2),0);
         }
    }
    else if(user1.target==5){
         selectitem(user1,con,conn);
    }
    else if(user1.target==6){
          string search="SELECT * FROM ITEM;";
          cout<<"sql语句:"<<search<<endl;
          auto search_res=mysql_query(con,search.c_str());
          auto result=mysql_store_result(con);
          int col=mysql_num_fields(result);//获取列数
          int row=mysql_num_rows(result);//获取行数
          cout<<""<<col<<""<<row<<endl;
          while(search_res==0&&row>0){
             cout<<"查询成功\n";
             auto info=mysql_fetch_row(result);//获取一行的信息
             cout<<"查询到项目ID:"<<info[0]<<"查询到项目名称:"<<info[1]<<"负责人名字:"<<info[2]<< "金额:"<<info[3]<<endl;
             user2.itemid=atoi(info[0]);
             strcpy(user2.itemname,info[1]);
             strcpy(user2.name,info[2]);
             user2.count=atoi(info[3]);
             send(conn,(char*)&user2,sizeof(user2),0);
             row--;
          }
          send(conn,(char*)&user2,sizeof(user2),0);
    }
    else if(user1.target==7){
          selectitem(user1,con,conn);
    }
    else if(user1.target==8){
    
    }
    else if(user1.target==9){
    
    }
    else if(user1.target==10){
    
    }
    mysql_close(con);          //关闭与mysql的连接
}

//子线程工作的静态函数
//注意，前面不用加static，否则会编译报错
void server::RecvMsg(int conn){
    //接收缓冲区
    char buffer[1000];
    //不断接收数据
    while(1)
    {
	user user1;
	memset(&user1,0,sizeof(user1));
	int len =recv(conn,(char*)&user1,sizeof(user),0);
	if(strcmp((char*)&user1,"exit")==0 || len<=0)
       {
                close(conn);
                sock_arr[conn]=false;
                break;
       }
        //cout<<user1.name<<user1.pass<<endl;
        //cout<<user1.target<<endl;
        HandleRequest(conn,user1);
    
    }
}

